package org.liaohailong.library.widget.interact

import android.app.Dialog
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import org.liaohailong.library.R

/**
 * Author: liaohailong
 * Date: 2019/3/13
 * Time: 2:08 PM
 * Description: 频道互动
 **/
class TVInteractDialogFragment : DialogFragment(), TVInteractView.OnTVInteractViewCallback {
    private var onTVInteractDialogCallback: OnTVInteractDialogCallback? = null
    private var firstMessage: Message? = null

    fun show(manager: FragmentManager, tag: String?, firstMessage: Message, onTVInteractDialogCallback: OnTVInteractDialogCallback?) {
        this.onTVInteractDialogCallback = onTVInteractDialogCallback
        this.firstMessage = firstMessage
        super.show(manager, tag)
    }

    private lateinit var tvInteractView: TVInteractView

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        context?.let {
            val dialog = Dialog(it, R.style.TVInteractDialogStyle)
            dialog.setContentView(R.layout.dialog_tv_interact)
            dialog.setCanceledOnTouchOutside(false)
            dialog.window?.apply {
                val attributes = attributes
                attributes.width = resources.getDimensionPixelSize(R.dimen.dp_413)
                attributes.height = ViewGroup.LayoutParams.MATCH_PARENT
                attributes.gravity = Gravity.END
                attributes.windowAnimations = R.style.InteractDialogAnim
                setAttributes(attributes)
                setDimAmount(0f)
                setBackgroundDrawableResource(android.R.color.transparent)
            }

            tvInteractView = dialog.findViewById(R.id.tv_interact_view)
            return dialog
        }
        return super.onCreateDialog(savedInstanceState)
    }

    override fun onStart() {
        super.onStart()
        tvInteractView.onTVInteractViewCallback = this
        if (firstMessage != null) {
            sendMessage(firstMessage!!)
            firstMessage = null
        }
    }

    fun sendMessage(message: Message) {
        tvInteractView.apply {
            addMessage(message)
            if (!isRunning) moveToNext()
        }
    }

    override fun onTVInteractMessageComplete() {
        dismiss()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        onTVInteractDialogCallback?.onTVInteractDialogDismiss(this)
    }

    interface OnTVInteractDialogCallback {
        fun onTVInteractDialogDismiss(dialog: TVInteractDialogFragment)
    }
}